package com.puppet.building182.handler.interceptor;

import com.alibaba.fastjson2.JSON;
import com.puppet.building182.pojo.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLDecoder;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if("user".equals(cookie.getName())) {
                        String value = cookie.getValue();
                        String decode= URLDecoder.decode(value, "UTF-8");
                        user= JSON.parseObject(decode, User.class);
                        request.getSession().setAttribute("user", user);
                    }
                }
            }
        }
if(user == null) {
    response.setContentType("application/json;charset=utf-8");
    response.setStatus(401);
    response.getWriter().write("{\"code\":401,\"msg\":\"未登录或登录已过期\"}");
    return false;
}
return true;

    }
}
//登录页面拦截